<?php
/**
 * 更新文档示例
 * Created by PhpStorm.
 * User: bimUser
 * Date: 2018/1/20
 * Time: 12:52
 */

require 'config.php';
require 'vendor/autoload.php';

// 实例化连接
$db = new MongoDB\Client("mongodb://{$cnf['USERNAME']}:{$cnf['PASSWD']}@{$cnf['HOST']}:{$cnf['PORT']}/{$cnf['DBNAME']}");

// 更新一个文档
// updateOne()方法更新匹配筛选条件的第一个文档
$collection = $db->test->users;
$collection->drop(); // 删除集合

$collection->insertOne(['name' => 'Bob', 'state' => 'ny']);
$collection->insertOne(['name' => 'Alice', 'state' => 'ny']);
$updateResult = $collection->updateOne(
    ['state' => 'ny'],
    ['$set' => ['country' => 'us']]
);

printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());


// 更新多个文档
$collection = $db->test->users;
$collection->drop();

$collection->insertOne(['name' => 'Bob', 'state' => 'ny', 'country' => 'us']);
$collection->insertOne(['name' => 'Alice', 'state' => 'ny']);
$collection->insertOne(['name' => 'Sam', 'state' => 'ny']);
$updateResult = $collection->updateMany(
    ['state' => 'ny'],
    ['$set' => ['country' => 'us']]
);

printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());
